package com.yzy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzy.annotation.UserLoginToken;
import com.yzy.entity.Collection;
import com.yzy.entity.Goods;
import com.yzy.service.CollectionService;
import com.yzy.util.Message;
import com.yzy.util.ResponseCode;
import com.yzy.util.TokenUtil;
import jdk.nashorn.internal.parser.Token;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Resource
    private CollectionService collectionService;

    @GetMapping("/all")
    public Object all(){

        List<Collection> list = collectionService.list();
        Map<String,List> map = new HashMap<>();
        map.put("data",list);
        return map;
    }
    @UserLoginToken
    @GetMapping("/collect")
    public Object collect(@RequestParam("goodsId") Integer goodsId){
        //这块能在后端获取用户id
        String userId= TokenUtil.getTokenUserId();
        Collection collection = new Collection();
        collection.setGoodsId(goodsId);
        collection.setUserId(Integer.valueOf(userId));

        collectionService.save(collection);

        Map<String,String> map = new HashMap<>();
        map.put("xyz","收藏成功");
        return ResponseCode.buildSuccess(map);
    }
    @UserLoginToken
    @GetMapping("/queryCollecting")
    public Object queryCollecting(){
        String userId= TokenUtil.getTokenUserId();
        List<Goods> goodsList = collectionService.queryCollecting(Integer.valueOf(userId));
        Map<String,List<Goods>> map = new HashMap<>();
        map.put("data",goodsList);

        return ResponseCode.buildSuccess(map);
    }

    @GetMapping("/cancelCollecting")
    public Object cancelCollecting(@RequestParam("goodsId") Integer goodsId){
        Integer userId = 1;

        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",goodsId);
        collectionService.remove(wrapper);

        Map<String,String> map = new HashMap<>();
        map.put("xyz","取消成功");

        return ResponseCode.buildSuccess(map);
    }

    @UserLoginToken
    @GetMapping("/collection/judgeCollecting")
    public Object judgeCollecting(@RequestParam("goodsId") Integer goodsId){
        Integer userId = Integer.valueOf(TokenUtil.getTokenUserId());
        if (collectionService.judgeCollecting(userId,goodsId))
            return ResponseCode.buildSuccess(Message.GOODS_ALREADY_COLLECTED);
        else return ResponseCode.buildFailed(Message.GOODS_NOT_COLLECTED);
    }

}
